import utils from '../../utils/util'
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    address: [], //地址数组,
    hasAddress: false
  },
  //添加地址
  addAddress() {
    wx.navigateTo({
      url: '../addressAdd/addressAdd',
    })
  },
  //删除地址
  delAddress(e) {
    wx.showModal({
      title: '提示',
      content: '您确认删除所选信息么',
      success: (res) => {
        if (res.confirm) {
          //获取需要删除的地址数组索引
          const idx = e.currentTarget.dataset.index;
          const address = this.data.address;
          //采用splice删除数组元素，并将删除的地址赋值给delAddress
          const delAddress = address.splice(idx, 1);
          //取出删除的地址id
          const _id = delAddress[0]._id;
          //发送服务端进行删除
          wx.request({
            url: `${app.globalData.server}/wxDelAddress`,
            data: {
              _id
            },
            success: res => {
              if (res.data == 'success') {
                //删除成功 刷新页面
                this.onShow()
              } else {
                //删除失败
                wx.showToast({
                  title: '删除失败',
                })
              }
            },
            fail: error => {
              console.log(error)
              wx.showToast({
                title: '删除失败',
              })
            }
          })
        }
      }
    })
  },
  //修改地址
  updateAddress(e) {
    const idx = e.currentTarget.dataset.index;
    const address = this.data.address[idx];
    wx.setStorageSync('addressInfo', address)
    wx.navigateTo({
      url: `../addressAdd/addressAdd`,
    })
  },
  //读取地址信息
  getAddress() {
    wx.showLoading({
      title: '地址加载中....',
    })
    wx.request({
      url: `${app.globalData.server}/wxAddress`,
      data: {
        openid: app.globalData.userInfo.openid
      },
      success: (res) => {
        wx.hideLoading()
        if (res.data.message == 'success') {
          this.setData({
            address: res.data.result,
            hasAddress: true
          })
        } else {
          wx.showToast({
            title: '服务器错误',
            icon: "error"
          })
        }
      },
      fail: (err) => {
        console.log(err)
        wx.showToast({
          title: '服务器错误',
        })
      }
    })
  },

  //选择地址
  selectAddress(e) {
    //获取页面传递的地址信息
    const address = e.currentTarget.dataset.address;
    //将地址信息中的楼栋与门牌号拼接成获得完整的快递地址
    const returnAddress = `${address.building}-${address.doorNum}`
    //获取页面栈（数组）
    const pages = getCurrentPages();
    //页面数组pages长度-2，为上一页
    const prevPage = pages[pages.length - 2];
    //将获得的地址赋值给上一页的form.address
    prevPage.setData({
      'form.address': returnAddress
    })
    //返回上一页
    wx.navigateBack({
      delta: 1,
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //清空地址缓存 防止修改地址信息时，未保存而后退时，未清理缓存
    wx.removeStorageSync('addressInfo');
    //判断登录
    if (!app.globalData.userInfo.openid) {
      wx.showModal({
        title: '温馨提示',
        content: '您尚未登陆，请先授权登录再试！',
        showCancel: false,
        success: () => {
          wx.switchTab({
            url: '../person/person',
          })
          return;
        }
      })
    } else {
      //调用getAddress方法，读取地址
      this.getAddress();
    }
  },
})